import axios from 'axios';
axios.defaults.withCredentials=true
//axios.defaults.baseURL = '/api'
//axios.defaults.headers.post['Content-Type'] = 'application/json';
import {  Loading } from 'vue-ydui/dist/lib.rem/dialog';
export default {
	data() {
		return {
			traceablityNo:'',
			config:config,
			isPhone:false,
			isPcPhone:false,
			userInfo:{},
			id:'',
			uuid:'',
		}
	},
	created(){
		
		if(localStorage.getItem('wst_lvzy_userInfo')&&localStorage.getItem('wst_lvzy_userInfo')!='{}'){
			this.userInfo=JSON.parse(localStorage.getItem('wst_lvzy_userInfo'))
		}else{
//			let params=''
//			if(this.config.channel||this.config.channel==0){
//				params=`channel=${this.config.channel}&`
//			}
//			if(this.$root.userInfo.oldUrlStr){
//				params = `${params}oldUrlStr=${this.$root.userInfo.oldUrlStr}`
//			}
//			console.log(this.$route)
//			console.log(this.$router.currentRoute)
//			console.log(this.$router)
//			if(this.$route.fullPath!='/'){
//				window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe1f972f1faee6756&redirect_uri=https://apply.aiwst.cn/view/dist/index.html?'+params+'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'
//			}
		}
		if(sessionStorage.getItem('wst_lvzy_openId')){
			var o={openId:sessionStorage.getItem('wst_lvzy_openId')};
			this.config = Object.assign({},this.config,o)
		}else{
			if(this.config.code){
//				this.getOpenId();
			}
		}
		
		if(localStorage.getItem('wst_lvzy_event')&&localStorage.getItem('wst_lvzy_event')!='{}'){
			this.submitEvent(JSON.parse(localStorage.getItem('wst_lvzy_event')))
		}
		console.log(this.userInfo)
	},
	mounted() {
		this.isPhone=!this.isPcOS()
		console.log('mixin')
		
	},
	methods: {
		//获取openId
		getOpenId(){
			return new Promise((resolve,reject)=>{
				this.$root.ajax({
					name:'wx/user', 
					type:'get',
					errormsg:true,
					closeDia:true,
					noCatch:true,
					params:{
						code:this.config.code
					},
					closeAllLoading:true,
				}).then((d)=>{
					//当code存在，但是过期了，重定向。
					if(d.openid){
						var o={openId:d.openid};
						sessionStorage.setItem('wst_lvzy_openId',d.openid)
						this.config = Object.assign({},this.config,o)
						resolve()
					}else{
						let params=''
						if(window.location.href.indexOf('?') >= 0 && window.location.search){
							params = window.location.href.split('?')[1].split('#/')[0]
							var stateParams= ''
							if(params){
								stateParams = ''
							}
						}
						let url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+this.config.appId+'&redirect_uri='+this.config.shareUrl+'?'+params+'&response_type=code&scope=snsapi_base&state='+stateParams+'#wechat_redirect'
						window.location.href=url
					}
						
				})
			})
				
		},
		//设置video图片
		videoImg(imgUrl){
			this.$nextTick(()=>{
				var videoObj = document.getElementsByTagName('video')
				if(videoObj.length>0){
					videoObj[0].setAttribute("poster",imgUrl)
				}
			})
		},
		wxShare({d={},query='',desc=''}={}){
			//D是一个对象，传过来的，query是参数，desc是描述
			var vm = this;
			console.log('d', d)
			console.log('query', query)
			console.log('desc', desc)
			wx.ready(function() {
				//https://apply.aiwst.cn/view/dist/index.html?query={a:1}&
				let linkUrl = `${vm.config.shareUrl}?${query}`
				var obj = {
					title: d.title,
					//link: `${vm.config.shareUrl}?${query}`,
					link: linkUrl,
					imgUrl: d.title_img,
					success: function() {
			
					},
					cancel: function() {
			
					}
				}
				wx.onMenuShareTimeline(obj)
				obj.desc = desc||d.remark;
				wx.onMenuShareAppMessage(obj)
				wx.onMenuShareQQ(obj)
				wx.onMenuShareQZone(obj)
				// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
			})			
		},
		allAjax({
			ajaxArr=[],
			loadingName='请稍后...'
		}={}){
			Loading.open(loadingName); 
			return new Promise((resolve,reject)=>{
				axios.all(ajaxArr.map((fn)=>{
					return fn()
				}))
				.then(axios.spread( (...objArr)=> {
				    console.log('两个请求都完成了')
				    Loading.close();
				    resolve(objArr)
				}))
			})
		},
		ajax({
			//左边代表那边传过来的参数，右边代表新建
			url: url,//地址前缀
			user:user,//user地址
			name:name,//名字
			params: params,//参数
			closeloadingOpen:loadingOpen=false,//真:表示单独关闭打开loading弹窗
			closeloadingClose:loadingClose=false,//真:表示单独关闭关闭loading弹窗
			closeAllLoading:closeAllLoading=false,//真:上面两个都不起作用，关闭所有loading
			loadingName='请稍后...',//loading名字
			type='post',//post,get提交参数,目前的需求就两种提交方式
			errormsg:error=false,//false,true真的时候返回错误信息
			closeDia:closeDia,//关闭错误的提示
			noCatch=false,//true表示捕获异常不显示提示，false则相反
			noToken=false,//true表示不传token,false表示穿
		} = {}) {
			var vm=this;
			if(closeAllLoading){
				loadingOpen=true
				loadingClose=true
			}
			if(this.userInfo&&name!='Index/wxLogin'&&!noToken){
				params.token?params.token=params.token:params.token=this.userInfo.token
			}
			
//			params.token='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTEyNjg0MTMsImV4cCI6MTYzNzU4MjAxMywidWlkIjoxMn0.ewZq5-LuEDIriJlQ0bSubuQ7PSn2g8RIhEW1j8oPzgU';
			//这里先写死
			url=url?url: this.config.api_url
			if(this.$root.config.dev){
				name = '/api/'+ name
			}
			if(user){
				url=url+'api/user/'+name
			}else{
				url=url+name
			}
			
			if(type == 'post') {
				return new Promise((resolve, reject) => {
					if(!loadingOpen){
						Loading.open(loadingName);
					}
					axios({
							method: type,
							url: url,
							headers: { "Content-Type": "application/x-www-form-urlencoded" },
							data: params,	
							transformRequest: [function(params) {
								var paramStr = '';
								for(var key in params) {
									paramStr += key + "=" + params[key] + "&";
								}
								return paramStr;
							}],
						}).then(response=> {
							if(!loadingClose){
								Loading.close();
							}
							if(response.data.code===0) {
								resolve(response.data)
							} else if(response.data.code===1000){
								vm.$router.push({
									name:'login'
								})
//								sessionStorage.setItem('wst_lvzy_userInfo','');
//								let params=''
//								//记录渠道
//								if(config.channel||config.channel==0){
//									params=`channel=${config.channel}&`
//								}
//								//登录不记录
//								if(window.location.href.indexOf('?') >= 0 && window.location.search){
//									params = window.location.href.split('?')[1].split('#/')[0]
//									var stateParams= ''
//									if(params){
//										stateParams = params.replace('=','_')
//									}
//								}
//								let url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe1f972f1faee6756&redirect_uri=https://apply.aiwst.cn/view/dist/index.html?'+params+'&response_type=code&scope=snsapi_userinfo&state='+stateParams+'#wechat_redirect'
//								window.location.href=url
							}else{
								if(error){
									resolve(response.data)
								}
								if(!closeDia){
									Loading.close();
									vm.$dialog.toast({
					                    mes: response.data.msg,
					                    timeout: 1500
					                });
								}
							}
						})
						.catch(function(error) {
							if(!loadingClose){
								Loading.close();
							}
							console.log(error);
							if(!noCatch){
								vm.$dialog.toast({
				                    mes: `接口异常`,
				                    timeout: 1500,
				                    callback:()=>{
				                    	Loading.close()
				                    }
				                });
							}
								
						});
				})
			} else {
				return new Promise((resolve, reject) => {
					if(!loadingOpen){
						Loading.open(loadingName);
					}
					axios.get(url, {
							params: params,
//							headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" }
						})
						.then(function(response) {
							if(!loadingClose){
								Loading.close();
							}
							if(response.data.code===0) {
								resolve(response.data)
							} else if(response.data.code===1000){
								vm.$router.push({
									name:'login'
								})
//								sessionStorage.setItem('wst_lvzy_userInfo','');
//								let params=''
//								//记录渠道
//								if(config.channel||config.channel==0){
//									params=`channel=${config.channel}&`
//								}
//								//登录不记录
//								if(window.location.href.indexOf('?') >= 0 && window.location.search){
//									params = window.location.href.split('?')[1].split('#/')[0]
//									var stateParams= ''
//									if(params){
//										stateParams = params.replace('=','_')
//									}
//								}
//								let url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe1f972f1faee6756&redirect_uri=https://apply.aiwst.cn/view/dist/index.html?'+params+'&response_type=code&scope=snsapi_userinfo&state='+stateParams+'#wechat_redirect'
//								window.location.href=url
							}else{
								if(error){
									resolve(response.data)
								}
								if(!loadingClose){
									Loading.close();
									vm.$dialog.toast({
					                    mes: response.data.msg,
					                    timeout: 1500
					                });
								}
								
							}
						})
						.catch(function(error) {
							if(!loadingClose){
								Loading.close();
							}
							console.log(error);
							if(!noCatch){
								vm.$dialog.toast({
				                    mes: `接口异常`,
				                    timeout: 1500,
				                    callback:()=>{
				                    	Loading.close()
				                    }
				                });
							}
						});
				})
			}
		},
		//处理金钱的0
		setMoneyZero(obj,str){
			if(obj[str]||obj[str]===0){
				if((obj[str]+'').indexOf('.')>=0){
					return obj[str]=obj[str].toFixed(1)
				}else{
					console.log(obj[str])
					return obj[str] = obj[str] + '.0'
				}
			}
		},
		//数据收集
		submitEvent({
			kind:kind,
			position=0,
			oid=this.id,
			lastFlg=false,
			localStorage=false, //判断是否有缓存
			event='view_begin',
			time=(parseInt(((new Date()).getTime())/1000)),
			uuid = this.uuid,
			uid=this.userInfo&&(JSON.stringify(this.userInfo)!='{}')?this.userInfo.me.id:0,
		}={}){
			let o ={
			    "event": event,      //事件名
			    "time": time,         //时间戳
			    "uuid": uuid,            //设备唯一ID
			    "uid": uid,                  //用户ID
			    "position": position,              //视频位置
			    "kind": kind,                  //浏览资源类型
			    "oid": oid                    //资源ID
			}
			if(lastFlg){
				o.event = 'view_end';
				if(!localStorage){
					o.time = (parseInt(((new Date()).getTime())/1000));
					//o.uuid = (parseInt((parseInt(new Date()-0))/1000))+''+(this.userInfo.me.id||0);
				}
			}
			this.ajax({
				name:'data/event',
				noToken:true,
				closeAllLoading:true,
				params:{
					event:JSON.stringify([o]),
					decode:1
				}
			}).then((d)=>{
				
			})
		},
		//判断是否电脑的模拟手机并且给swiper加onClick或者onTap事件
		getOS() {
			if(this.isPcOS()) {
				return 'pcOS'
			} else {
				return 'sjOS'
			}
		},
		//判断操作系统
		isPcOS() {
			var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
			if(isWin) return 'Win'; //'Win'
			var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
			if(isMac) return 'Mac'; //'Mac'
			var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
			if(isUnix) return 'Unix'; //'Unix'
			var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
			if(isLinux) return 'Linux'; //'Linux'
			return 'Phone'
		},
		//获取是否PC端
		isPc() {
			var ua = navigator.userAgent;
			if((ua.match(/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i))) {
				if(/iPhone|iPad|iPod/.test(ua)) {
					//'ios'
					return 'ios'
				} else if(/Android/.test(ua)) {
					//'android'
					return 'android'
				}
			} else {
				//'pc'
				return 'pc'
			}
		},
		//是否微信端
		isWeiXin(){
			var ua = navigator.userAgent;
			if(ua.match(/MicroMessenger/i) != 'MicroMessenger'){
				return false 
			}else{
				return true
			}
		},
		//获取手机名称
		getDeviceInfo(ua, a) {
			//		var ua = navigator.userAgent;
			//		var mm = ['iPhone', 'iPad', 'iPod', 'Nexus', 'BenQ-Siemens', 'Meizu', 'Xiaomi', 'BlackBerry', 'CoolPad', 'Dell', 'HTC', 'Huawei', 'Kindle', 'K-Touch', 'Lenovo', 'LG', 'Motorola', 'Nintendo', 'Nokia', 'Onda', 'OPPO', 'OLPC', 'Palm', 'PlayStation', 'Samsung', 'SonyXperia', 'SonyEricsson', 'vivo', 'ZTE', 'UbuntuPhone', 'UbuntuTablet', 'WindowsPhone']
			var devices = a,
				device,
				c,
				i = 0;
			while(device = devices[i++]) {
				var d = new RegExp("(" + device + ")", "i");
				if(d.test(ua.toLowerCase())) c = device;
			}
			switch(c) {
				case undefined:
					c = 'Android';
					break;
				case 'iPhone OS':
					c = 'iOS';
					break;
			}
			return c;
		},
		//获取时间格式化
		getDate(date,obj={}) {
			var str='';
			obj.str?str=obj.str:str='-'
			var year = date.getFullYear()
			var month = date.getMonth() + 1
			var day = date.getDate()
			var h = date.getHours();
			var min = date.getMinutes();
			var s = date.getSeconds()
			var d=''
			if(obj.allTime){
				if(obj.allTime==2){
					d =  (month < 10 ? '0' + month : month) + str + (day < 10 ? '0' + day : day)
					+' ' + (h < 10 ? '0' + h : h) + ":" + (min < 10 ? '0' + min : min) 
				}else{
					
					d = date.getFullYear() + str + (month < 10 ? '0' + month : month) + str + (day < 10 ? '0' + day : day)
					+' ' + (h < 10 ? '0' + h : h) + ":" + (min < 10 ? '0' + min : min) + ":" + (s < 10 ? '0' + s : s)
				}
			}else{
				d = date.getFullYear() + str + (month < 10 ? '0' + month : month) + str + (day < 10 ? '0' + day : day)
			}
			return d
		},
		videoPlayFlg(item){
			return new Promise((resolve,reject)=>{
				this.$root.ajax({
					name: 'video/auth',
					errormsg:true,
					closeDia:true,
					params: {
						id	: item.id
					}
				}).then((d) => {
					if(d.code == 2000){
						this.$dialog.confirm({
		                    title: '温馨提示',
		                    mes: `<span style='color:#A1A1A1;'>${d.msg}</span>`,
		                    opts: [
		                        {
		                            txt: '知道了',
		                            stay: false,
		                            color: '#35BF7E',
		                            callback: () => {
		                            	
				                    }
		                        },
		                    ]
		                });
		                resolve(d)
					}else{
						if(item.isNoRouter){
							resolve(d)
						}else{
							this.$router.push({
								name:'courseVideoDetail',
								query:{
									id:item.id
								}
							})
						}
						
					}
				})
			})
		},
		hqcPlayFlg(item){
			return new Promise((resolve,reject)=>{
				this.$root.ajax({
					name: 'hqc/auth',
					errormsg:true,
					closeDia:true,
					params: {
						
					}
				}).then((d) => {
					if(d.code == 2000){
						this.$dialog.confirm({
		                    title: '温馨提示',
		                    mes: `<span style='color:#A1A1A1;'>${d.msg}</span>`,
		                    opts: [
		                        {
		                            txt: '知道了',
		                            stay: false,
		                            color: '#35BF7E',
		                            callback: () => {
		                            	
				                    }
		                        },
		                    ]
		                });
					}else{
						if(item.isNoRouter){
							resolve(d)
						}else{
							this.$router.push({
								name:'courseVideoDetail',
								query:{
									id:item.id
								}
							})
						}
						
					}
				})
			})
		},
		getNumDate(n,str){
			var date=new Date();
			var d =''
			if(str=='month'){
				date.setMonth(date.getMonth()-n);
				var month = date.getMonth() + 1
				d = date.getFullYear() + '-' + (month < 10 ? '0' + month  : month )
			}else{
				date.setDate(date.getDate()-n);
				var month = date.getMonth() + 1
				var day = date.getDate()
				
				if(str=='year'){
					d = date.getFullYear()+''
				}else{
					d = date.getFullYear() + '-' + (month < 10 ? '0' + month  : month ) + '-' + (day < 10 ? '0' + day : day)
				}
			}
			return d
		},
		//导航栏路由跳转
		onClickLeft() {
			window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
		},
		onClickRight(){
			this.$router.push({name:'index',query:{traceablityNo:this.$route.query.traceablityNo}})
		},
		//获取url参数
		getQueryString(name) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
			var r = window.location.search.substr(1).match(reg);
			if(r != null) {
				return unescape(r[2]);
			}
			return null;
		},
		//获取来源渠道
		sources() {
			var ua = navigator.userAgent;
			var f = this.getQueryString('f');
			if(f != null) {
				return f;
			}
			var wxFrom = this.getQueryString('from');
			if(wxFrom != null) {
				if(wxFrom == 'groupmessage') {
					return 'Wechat';
				} else if(wxFrom == 'singlemessage') {
					return 'Weixin';
				}
			}
			if(f == null && wxFrom == null) {
				var str='FitIdx'
				if(ua.match(/QQ/i) == "QQ") {
					//return "QQ";
					str='QQ'
				}
				if(ua.match(/MicroMessenger/i) == "MicroMessenger") {
					//return "Weixin";
					str='Weixin'
				}
				return str
			}
		},
		carReg(str){
			return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str)
		}
	},
}